package com.fw.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;

/**
 * Update Spring managed properties
 */
public class SpringPropertyUpdater implements ApplicationContextAware {

    private ConfigurableApplicationContext ctx;
    private static final String LOCATION_PROPERTY = "location";
    private static final Log log = LogFactory.getLog(SpringPropertyUpdater.class);

    /**
     * Update managed properties with new value
     */
    public void updateProperties(String name, Properties props, String comments) {
	ConfigurableListableBeanFactory fb = ctx.getBeanFactory();
	BeanDefinition bf = fb.getBeanDefinition(name);
	TypedStringValue location = (TypedStringValue) bf.getPropertyValues().getPropertyValue(LOCATION_PROPERTY).getValue();
	Resource res = ctx.getResource(location.getValue());
	try {
	    File file = res.getFile();
	    props.store(new FileOutputStream(file), comments);
	} catch (IOException e) {
	    e.printStackTrace();
	    log.error(e);
	}
    }

    /**
     * {@inheritDoc}
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	this.ctx = (ConfigurableApplicationContext) applicationContext;

    }
}
